'use client';
import { useState } from 'react';
import { useWriteContract, useAccount } from 'wagmi';
import { parseUnits } from 'viem';
import MiniVault_ABI from '../abis/MiniVault.json';
import contractAddresses from '../constants/contracts.json'; // 自动生成的地址

const VAULT_ADDRESS = contractAddresses.MiniVault;

export function WithdrawForm() {
  const { address } = useAccount();
  const [share, setShare] = useState('');
  const [submitted, setSubmitted] = useState(false);

  const { writeContract, isPending, isSuccess, error } = useWriteContract();

  const handleWithdraw = () => {
    if (!share) return;
    writeContract({
      address: VAULT_ADDRESS as `0x${string}`,
      abi: MiniVault_ABI.abi,
      functionName: 'withdraw',
      args: [parseUnits(share, 6)],
      account: address,
    });
    setSubmitted(true);
  };

  return (
    <div className="space-y-2">
      <input
        type="number"
        min="0"
        placeholder="Share Amount"
        value={share}
        onChange={(e) => setShare(e.target.value)}
        className="w-full px-4 py-2 border border-gray-200 rounded-xl bg-gray-100 placeholder-gray-400 
        focus:outline-none focus:ring-2 focus:ring-blue-400 placeholder:text-sm placeholder:font-light text-black"
      />
      <button
        onClick={handleWithdraw}
        disabled={!share || isPending}
        className="bg-orange-400 hover:bg-orange-500 text-white font-semibold py-2 rounded-xl w-full"
      >
        {isPending ? 'Withdrawing...' : 'Withdraw'}
      </button>
      {isSuccess && submitted && (
        <p className="text-green-600">Withdraw successful! {share}</p>
      )}
      {error && <p className="text-red-600">Error: {error.message}</p>}
    </div>
  );
}
